package com.rh.bmw4s.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rh.bmw4s.R;
import com.rh.bmw4s.bean.BaseBean;
import com.rh.bmw4s.bean.RegisterBean;
import com.rh.bmw4s.bean.ResBean;
import com.rh.bmw4s.comm.ConfigValue;
import com.rh.bmw4s.comm.Constant;
import com.rh.bmw4s.utills.CheckUtil;
import com.rh.bmw4s.utills.DealResult;
import com.rh.bmw4s.utills.DialogUtils;
import com.rh.bmw4s.utills.LogUtils;
import com.rh.bmw4s.utills.SPUtils;
import com.rh.bmw4s.utills.TimeCount;
import com.rh.bmw4s.utills.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

public class LoginRegActivity extends BaseActivity {

    @BindView(R.id.img_head)
    ImageView imgHead;
    @BindView(R.id.tv_find_psw)
    TextView tvFindPsw;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_yzm)
    EditText etYzm;
    @BindView(R.id.tv_get_yzm)
    TextView tvGetYzm;
    @BindView(R.id.et_psw)
    EditText etPsw;
    @BindView(R.id.et_psw_confirm)
    EditText etPswConfirm;
    @BindView(R.id.tv_register)
    TextView tvRegister;
    ViewGroup layoutLogin;
    ViewGroup layoutRegister;
    @BindView(R.id.et_reg_name)
    EditText etRegName;
    @BindView(R.id.et_reg_phone)
    EditText etRegPhone;
    @BindView(R.id.et_reg_psw)
    EditText etRegPsw;
    @BindView(R.id.img_eye)
    ImageView imgEye;
    @BindView(R.id.textView)
    TextView textView;
    @BindView(R.id.view_1)
    View view1;
    @BindView(R.id.view_line_login)
    View lineLogin;
    @BindView(R.id.rel_login_group)
    RelativeLayout relLoginGroup;
    @BindView(R.id.view_line_register)
    View lineRegister;
    @BindView(R.id.rel_register_group)
    RelativeLayout relRegisterGroup;
    private TimeCount timeCount;
    private boolean isSee = false;
    private Handler mHandler = null;
    private Gson gson;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_reg);
        ButterKnife.bind(this);
        gson = new Gson();
        initView();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (msg.what == 1) {
                    layoutLogin.setVisibility(View.VISIBLE);
                    layoutRegister.setVisibility(View.GONE);
                    lineLogin.setVisibility(View.VISIBLE);
                    lineRegister.setVisibility(View.GONE);
                } else {
                    layoutLogin.setVisibility(View.GONE);
                    layoutRegister.setVisibility(View.VISIBLE);
                    lineLogin.setVisibility(View.GONE);
                    lineRegister.setVisibility(View.VISIBLE);
                }
            }
        };
    }


    private void initView() {
        timeCount = new TimeCount(tvGetYzm, 2 * 60 * 1000, 1000);
        layoutLogin = (ViewGroup) findViewById(R.id.layout_login);
        layoutRegister = (ViewGroup) findViewById(R.id.layout_register);

        etRegPsw.setTransformationMethod(PasswordTransformationMethod.getInstance());     //密文
        etPswConfirm.setTransformationMethod(PasswordTransformationMethod.getInstance());  //明文
    }

    @OnClick({R.id.rel_login_group, R.id.rel_register_group, R.id.tv_confirm, R.id.tv_get_yzm,
            R.id.tv_register, R.id.tv_find_psw, R.id.img_eye})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rel_login_group:
                mHandler.sendEmptyMessage(1);
                break;
            case R.id.rel_register_group:
                mHandler.sendEmptyMessage(2);
                break;
            case R.id.tv_confirm:
                getLoginInput();
                break;
            case R.id.tv_get_yzm:
                String phone = etRegPhone.getText().toString();
                if (!CheckUtil.isMobileNO(phone)) {
                    ToastUtils.toastForShort(LoginRegActivity.this, "请先输入手机号码");
                    return;
                }
                getYzm(phone);
                break;
            case R.id.tv_register:
                getInputDatas();
                break;
            case R.id.tv_find_psw:
                startActivity(new Intent(LoginRegActivity.this, PswFindActivity.class));
                break;
            case R.id.img_eye:
                if (isSee) {
                    etPsw.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    isSee = false;
                    imgEye.setBackgroundResource(R.mipmap.eye);
                } else {
                    etPsw.setInputType(InputType.TYPE_CLASS_TEXT);
                    isSee = true;
                    imgEye.setBackgroundResource(R.mipmap.eye_open);
                }
                break;
        }
    }

    private void getLoginInput() {
        String name = etName.getText().toString();
        String psw = etPsw.getText().toString();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(psw)) {
            ToastUtils.toastForShort(LoginRegActivity.this, "请输入用户名密码");
            return;
        }
        login(name, psw);
    }

    private void login(String name, String psw) {
        OkGo.<String>post(Constant.LOGIN)
                .tag(this)
                .params("username", name)
                .params("password", psw)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("eee", response.body().toString());
                        BaseBean<ResBean> bean = DealResult.getInstace().dealData(LoginRegActivity.this, response, new TypeToken<BaseBean<ResBean>>() {
                        }.getType());
                        ToastUtils.toastForShort(LoginRegActivity.this, bean.getMsg());
                        if (bean.getStatus() == Constant.SUCESS) {
                            int user_id = bean.getData().getUser_id();
                            SPUtils.getInstance().put(ConfigValue.userId, user_id);
                            //设置推送别名
                            JPushInterface.setAlias(LoginRegActivity.this, 12, "bm_" + user_id);

                            Intent i = new Intent();
                            i.setClass(LoginRegActivity.this, MainActivity.class);
                            startActivity(i);
                            LoginRegActivity.this.finish();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("eee", "dgdfgdfhg");
                        ToastUtils.toastForShort(LoginRegActivity.this, "网络信号差，连接超时!");
                        super.onError(response);
                    }
                });
    }

    private void getYzm(String phone) {
        OkGo.<String>post(Constant.YZM)
                .tag(this)
                .params("mobile", phone)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        BaseBean<String> bean = DealResult.getInstace().dealData(LoginRegActivity.this, response, new TypeToken<BaseBean<String>>() {
                        }.getType());
                        timeCount.start();
                        ToastUtils.toastForShort(LoginRegActivity.this, bean.getMsg());
                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(LoginRegActivity.this, "网络信号差，连接超时!");
                        super.onError(response);
                    }
                });
    }

    private void getInputDatas() {
        String name = etRegName.getText().toString();
        String phone = etRegPhone.getText().toString();
        String yzm = etYzm.getText().toString();
        String psw = etRegPsw.getText().toString();
        String pswConfirm = etPswConfirm.getText().toString();
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(phone) || TextUtils.isEmpty(yzm) || TextUtils.isEmpty(psw) || TextUtils.isEmpty(pswConfirm)) {
            ToastUtils.toastForShort(LoginRegActivity.this, "请完善信息");
            return;
        }
        if (!CheckUtil.checkPassword(psw) || psw.length() < 6) {
            ToastUtils.toastForShort(LoginRegActivity.this, "密码格式不正确");
            return;
        }
        if (!TextUtils.equals(psw, pswConfirm)) {
            ToastUtils.toastForShort(LoginRegActivity.this, "密码不一致");
            return;
        }
        register(name, phone, yzm, psw);

    }

    private void register(String name, String phone, String yzm, String psw) {
        OkGo.<String>post(Constant.REGISTER)
                .tag(this)
                .params("tel", phone)
                .params("password", psw)
                .params("yanpass", yzm)
                .params("username", name)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        LogUtils.d("eee", response.body().toString());

                        RegisterBean registerBean = gson.fromJson(response.body().toString(), RegisterBean.class);
                        ToastUtils.toastForShort(LoginRegActivity.this, registerBean.getMsg());
                        if (registerBean.getStatus() == Constant.SUCESS) {
                            //注册成功，要先进行登录
                            mHandler.sendEmptyMessage(1);
                        }

                    }

                    @Override
                    public void onError(Response<String> response) {
                        DialogUtils.stopProgressDlg();
                        ToastUtils.toastForShort(LoginRegActivity.this, getString(R.string.bad_net));
                        super.onError(response);
                    }
                });
    }


}
